<?php
namespace app\know\controller;

use app\know\controller\AdminKnowBaseController;
use app\know\validate\PaperValidate;
use app\know\validate\PaperCategoryValidate;
use app\know\validate\NewWordQuestionValidate;
use app\know\validate\NewWordExampleValidate;
use app\know\validate\NewWordExpandValidate;
use app\know\model\ChapterModel;
use app\know\model\SysConfigModel;
use app\know\model\PaperModel;
use app\know\model\PaperCategoryModel;
use app\know\model\PaperQuestionModel;
use app\know\model\MaterialModel;
use app\know\model\QuestionModel;

use think\facade\Db;
use app\user\model\AssetModel;

/**
 * Class AdminNewWordController 生词管理控制器
 * @package app\know\controller
 */
class AdminPaperController extends AdminKnowBaseController
{
    /**
     * 教材管理
     * @adminMenu(
     *     'name'   => '试卷管理',
     *     'parent' => 'know/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> false,
     *     'order'  => 37000,
     *     'icon'   => '',
     *     'remark' => '试卷管理',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $content = hook_one('know_admin_paper_index_view');

        if (!empty($content)) 
		{
            return $content;
        }

		$chapter_uuid = $this->request->param('chapter_uuid', '');
        $material_uuid = $this->request->param('material_uuid', '');
        $nav = $this->request->param('nav', 'list');

        $where = ['is_delete' => 0];
        $materials = MaterialModel::where($where)
                                    ->order('order_number', 'desc')
                                    ->select();
        
        $w = ['is_delete' => 0, 'type' => 'QUESTION_TYPE'];
        $question_types = SysConfigModel::where($w)->select();
          
        $this->assign('question_types', $question_types);
		$this->assign('materials', $materials);
        $this->assign('material_uuid', $material_uuid);
        $this->assign('chapter_uuid', $chapter_uuid);
        $this->assign('nav', $nav);
        
        return $this->fetch();
    }
	
    public function list()
    {
        $chapter_uuid = $this->request->param('chapter_uuid', '');
        $pageNumber = $this->request->param('pageNumber', 1, 'intval');
        $pageSize = $this->request->param('pageSize', 10, 'intval');

        $where = ['is_delete' => 0];
        if ($chapter_uuid)
        {
            $where['chapter_uuid'] = $chapter_uuid;
        }

        $count = PaperModel::where($where)->count();
        $rows = PaperModel::where($where)->page($pageNumber, $pageSize)->select();

        $m = new ChapterModel(); 
        $TYPE_ARR = ['ZJLX' => '章节类型'];  
		foreach($rows as &$v) 
		{
            if ($v['chapter_uuid'] && $v['material_uuid'])
            {
                $v['chapter_name'] = $m->getChapterPath($v['chapter_uuid'], $v['material_uuid']);
                $material = MaterialModel::where(['uuid' => $v['material_uuid'], 'is_delete' => 0])->find();
                $v['teaching_name'] = $material ? $material['name'] : '';
            }
            else
            {
                $v['chapter_name'] = '';
                $v['teaching_name'] = '';
            }
            $v['type_name'] = $TYPE_ARR[$v['type']]??'';
        }
		
        $this->success('', null, ['rows' => $rows, 'total' => $count]);
    }
    
	public function add()
    {
        $param = $this->request->param();

        $user = $this->getAdminUser();
        $param['create_user'] = $user['user_login'];

        try 
		{
			$model = new PaperModel();
			$param['uuid'] = $model->getUUID();
        } 
		catch (ValidateException $e) 
		{
            $this->error($e->getError());
        }

        Db::startTrans();
        try 
        {
            
            $this->validateFailError($param, 'Paper.type');
            if ($param['type'] === 'ZJLX')
            {
                $this->validateFailError($param, 'Paper.addZJLX');
            }
            
            $row = PaperModel::create($param);
            if (empty($row)) 
            {
                throw new Exception('试卷添加失败');
            }
            $this->log('aaa-333');
            
            Db::commit();
        } 
        catch (ValidateException $e) 
        {
            Db::rollback();
            $this->error($e->getError());
        }

        $this->opLog([
            'table_name' => $model->getTableName(),
            'sql' => PaperModel::getLastSql(),
            'create_user' => $user['user_login'],
        ]);
        $this->success('添加成功');
    }
	
	public function delete()
    {
        $param = $this->request->param();
        $uuid = $this->request->param('uuid', '');
        
        try 
		{
            $this->validateFailError($param, 'Paper.delete');
        } 
		catch (ValidateException $e) 
		{
            $this->error($e->getError());
        }

        $user = $this->getAdminUser();

        try 
		{
            $d['is_delete'] = 1;
            $d['modify_user'] = $user['user_login'];
            $d['modify_datetime'] = date("Y-m-d H:i:s");

            PaperModel::where('uuid', 'in', preg_split("/[\s;,]/", $uuid))->save($d);
            $this->opLog([
                'table_name' => (new PaperModel())->getTableName(),
                'sql' => PaperModel::getLastSql(),
                'create_user' => $user['user_login'],
                'before_data' => json_encode($uuid),
            ]);
        } 
		catch (\Throwable $th) 
		{
            $this->error($th->getMessage());
        }
        $this->success('已删除');
    }
	
	public function edit()
    {
        $param = $this->request->param();
        $uuid = $this->request->param('uuid', '');
        
        try 
		{
            $this->validateFailError($param, 'paper.editZJLX');
        } 
		catch (ValidateException $e) 
		{
            $this->error($e->getError());
        }

        $user = $this->getAdminUser();
        $param['modify_user'] = $user['user_login'];
        $param['modify_datetime'] = date("Y-m-d H:i:s");
        
        Db::startTrans();
        try 
		{
            $d = PaperModel::where(['uuid' => $uuid])->find();
            if ($d['type'] === 'ZJLX')
            {
                PaperModel::update($param, ['uuid' => $uuid], PaperModel::$UpdateField_ZJLX);
            }
        
            $this->opLog([
                'table_name' => (new PaperModel())->getTableName(),
                'sql' => PaperModel::getLastSql(),
                'create_user' => $user['user_login'],
                'before_data' => json_encode($d),
            ]);
            Db::commit();
        } 
		catch (\Throwable $th) 
		{
            Db::rollback();
            $this->error($th->getMessage());
        }
        $this->success('修改成功');
    }

    public function getItem()
    {
        $uuid = $this->request->param('uuid', '');

        $w = ['is_delete' => 0, 'uuid' => $uuid];
        $row = PaperModel::where($w)->find();

        $this->success('', null, $row);
    }

    public function maxOrder()
    {
        $order = PaperModel::max('order_number');
        $this->success('', '', $order);
    }

    public function search()
    {
        $txt = $this->request->param('txt', '');

        $model = new NewWordModel();
        $rows = $model->where('a.content','like', $txt . '%')
                    ->alias('a')
                    ->page(1, 10)
                    ->select()
                    ->toArray();

        foreach ($rows as $k => $v)
        {
            if ($v['audio_asset_id'])
            {
                $audio_asset = AssetModel::find($v['audio_asset_id']);
                $rows[$k]['audio_asset_url'] = $audio_asset ? cmf_get_file_download_url($audio_asset["file_path"]) : '';
            }
            else
            {
                $rows[$k]['audio_asset_url'] = ''; 
            }
        }

        $this->success('', null, $rows);
    }

    public function questionSave()
    {
        $param = $this->request->param();
        $paperId = $this->request->param('paperId'); 
        $questionStr = $this->request->param('question');
        $categoryArr = json_decode(htmlspecialchars_decode($questionStr), true); 
        
        $user = $this->getAdminUser();
        $param['create_user'] = $user['user_login'];

        $w_c['paper_uuid'] = $paperId;
        $categoryList = PaperCategoryModel::where($w_c)->select();

        $w_q['paper_uuid'] = $paperId;
        $questionList = PaperQuestionModel::where($w_q)->select();

        // 如果删除分类，删除相关试题
        Db::startTrans();
        try 
        {
            $model_cate = new PaperCategoryModel();

            $quesArr = [];
            $cateArr = [];
            $pad = -1;
            foreach ($categoryArr as $v)
            {
                $cate_f = false;
                foreach ($categoryList as $v1)
                {
                    if ($v['uuid'] === $v1['uuid'])
                    {
                        $cate_f = $v1;break;
                    }
                }

                $cate_uuid = '';
                if ($cate_f === false)
                {
                    // 添加分类
                    $pad += 1;
                    $cate['paper_uuid'] = $paperId;
                    $cate['uuid'] = $model_cate->getUUID(32, $pad);
                    $cate['name'] = $v['name'];
                    $cate['type_code'] = $v['type_code'];
                    $cate['order_number'] = $v['order_number'];
                    $cate['create_user'] = $user['user_login'];
                    $cate['create_datetime'] = date("Y-m-d H:i:s");
                    array_push($cateArr, $cate);
                    $cate_uuid = $cate['uuid'];

                    foreach ($v['questionList'] as $v5)
                    {
                        array_push($quesArr, [
                            'paper_uuid' => $paperId,
                            'paper_category_uuid' => $cate_uuid,
                            'question_uuid' => $v5['uuid'],
                            'create_user' => $user['user_login'],
                            'create_datetime' => date("Y-m-d H:i:s"),
                        ]);
                    }
                }
                else
                {
                    // 修改分类
                    $cate_s['name'] = $v['name'];
                    $cate_s['type_code'] = $v['type_code'];
                    $cate_s['order_number'] = $v['order_number'];
                    $cate_s['modify_user'] = $user['user_login'];
                    $cate_s['modify_datetime'] = date("Y-m-d H:i:s");
                    PaperCategoryModel::update($cate_s, ['id' => $cate_f['id']]);
                    $cate_uuid = $cate_f['uuid'];

                    foreach ($v['questionList'] as $v8)
                    {
                        $ext = false;
                        foreach ($questionList as $v9)
                        {
                            if ($v8['uuid'] === $v9['question_uuid'])
                            {
                                $ext = true;break;
                            }
                        }

                        if ($ext === false) 
                        {
                            array_push($quesArr, [
                                'paper_uuid' => $paperId,
                                'paper_category_uuid' => $cate_uuid,
                                'question_uuid' => $v8['uuid'],
                                'create_user' => $user['user_login'],
                                'create_datetime' => date("Y-m-d H:i:s"),
                            ]);
                        }
                    }
                }

                // 处理分类试题
                // 处理分类试题
            }

            if (count($cateArr) > 0)
            {
                $row = PaperCategoryModel::insertAll($cateArr);
                if (empty($row))
                {
                    throw new Exception('试卷分类添加失败');
                }
            }

            if (count($quesArr) > 0)
            {
                $row = PaperQuestionModel::insertAll($quesArr);
                if (empty($row))
                {
                    throw new Exception('试卷试题添加失败');
                }
            }
            
            $uuids_cate_del = [];
            $ids_cate_del = [];
            $ids_ques_del = [];
            foreach ($categoryList as $v2)
            {
                $cate_f = false;
                foreach ($categoryArr as $v3)
                {
                    if ($v2['uuid'] === $v3['uuid'])
                    {
                        $cate_f = true;break;
                    }
                }
                if ($cate_f === false)
                {
                    // 删除分类
                    array_push($ids_cate_del, $v2['id']);
                    array_push($uuids_cate_del, $v2['uuid']);
                }
            }

            $uuids_ques = [];
            foreach ($categoryArr as $v3)
            {
                foreach ($v3['questionList'] as $v7)
                {
                    array_push($uuids_ques, $v7['uuid']);
                }
            }
            foreach ($questionList as $v4)
            {
                if (in_array($v4['question_uuid'], $uuids_ques) === false)
                {
                    array_push($ids_ques_del, $v4['id']);
                }
            }

            if (count($ids_cate_del) > 0)
            {
                $row = PaperCategoryModel::where('id','in', $ids_cate_del)->delete();
                if (empty($row))
                {
                    throw new Exception('试卷分类删除失败');
                }
            }
            if (count($ids_ques_del) > 0)
            {
                $row = PaperQuestionModel::where('id','in', $ids_ques_del)->delete();
                if (empty($row))
                {
                    throw new Exception('试卷试题删除失败');
                }
            }
            Db::commit();
        } 
        catch (ValidateException $e) 
        {
            Db::rollback();
            $this->error($e->getError());
        }
        $this->success('保存成功');
    }
	
    public function question()
    {
        $paperId = $this->request->param('paperId'); 

        $w_c['paper_uuid'] = $paperId;
        $categoryList = PaperCategoryModel::where($w_c)->select()->toArray();

        $w_q['paper_uuid'] = $paperId;
        $questionList = PaperQuestionModel::where($w_q)->select();
       
        $model = new QuestionModel();
        foreach($categoryList as &$v)
        {
            $v['questionList'] = [];
            foreach($questionList as $q)
            {
                if ($q['paper_category_uuid'] === $v['uuid'])
                {
                    $q0 = $model->getQuestionMerge('', $q['question_uuid']);
                    array_push($v['questionList'], $q0);
                }
            }
        }
        
        $this->success('', null, $categoryList);
    }
	
}
